package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.finance.domain.TFreightBillInfo;
import com.ruoyi.finance.domain.TSalaryBillInfo;
import com.ruoyi.finance.service.ITFreightBillInfoService;
import com.ruoyi.finance.service.ITFreightWayBillRelService;
import com.ruoyi.finance.service.ITSalaryBillInfoService;
import com.ruoyi.finance.service.ITSalaryWayBillRelService;
import com.ruoyi.waybill.domain.TWayBillExt;
import com.ruoyi.waybill.service.ITWayBillExtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.time.LocalDate;

import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.utils.Threads.sleep;

/**
 * 定时任务，运费账单，任务
 * 
 * @author ruoyi
 */
@Component("fbTask")
public class FbTask
{
    @Autowired
    private ITWayBillExtService tWayBillExtService;

    @Autowired
    private ITFreightBillInfoService tFreightBillInfoService;

    @Autowired
    private ITFreightWayBillRelService tFreightWayBillRelService;

    private static Logger logger = LoggerFactory.getLogger(FbTask.class);

    /**
     * 统计月运费单，无参
     */

    public void statisticMonthFreightBill()
    {
        logger.debug("统计，月运费单，月账单，按结算客户，开始 ...");
        /**
         * 计算当前日期，前一月日期
         */
        LocalDate currentDate = LocalDate.now();
        logger.debug("当前日期: " + currentDate);
        LocalDate lastMonthDate = currentDate.minusMonths(1);
        logger.debug("上月日期: " + lastMonthDate);
        LocalDate lastMonthFirstDay = lastMonthDate.with(TemporalAdjusters.firstDayOfMonth());
        logger.debug("上个月第一天：" + lastMonthFirstDay);
        LocalDate lastMonthLastDay = lastMonthDate.with(TemporalAdjusters.lastDayOfMonth());
        logger.debug("上个月最后一天：" + lastMonthLastDay);

        TWayBillExt tWayBillExt = new TWayBillExt();
        Double monthFreightWeightTotal = 0.0;
        Double monthFreightAmountTotal = 0.0;
        TFreightBillInfo tFreightBillInfo = new TFreightBillInfo();
        String monthFreightBillNumber;
        Long monthFreightBillId = 0L;
        List<Long> wayBillIds = new ArrayList<>();

        /**
         * 按录单日期，筛选结费客户列表
         */
        List<String> freightSettlementCustomers = tWayBillExtService.selectStatisticFieldByRecordDate(1 /*结算客户*/, Date.valueOf(lastMonthFirstDay), Date.valueOf(lastMonthLastDay));
//        logger.debug("结费客户列表：freightSettlementCustomers = " + freightSettlementCustomers);

        /**
         * 遍历结算客户，运单
         */
        for(String freightSettlementCustomer : freightSettlementCustomers)
        {
            /**
             * 按车牌号。录单日期，查询运单
             */
            tWayBillExt.setFreightSettlementCustomer(freightSettlementCustomer);
            logger.debug("结算客户：freightSettlementCustomer = " + freightSettlementCustomer);
            List<TWayBillExt> wayBillExts = tWayBillExtService.selectTWayBillExtListUsedByMonthStatistic(1 /*车牌号码*/, tWayBillExt, Date.valueOf(lastMonthFirstDay), Date.valueOf(lastMonthLastDay));
//            logger.debug("运单列表：wayBillExts = " + wayBillExts);
            /**
             * 合计运费，记录运单ID
             */
            for(TWayBillExt wayBillExt : wayBillExts) {
                monthFreightWeightTotal = monthFreightWeightTotal + wayBillExt.getFreightWeight();
                monthFreightAmountTotal = monthFreightAmountTotal + wayBillExt.getFreightAmount();
                wayBillIds.add(wayBillExt.getWayBillId());
            }

            /**
             * 保护，goodsIds，为空，直接退出
             */
            if(wayBillIds.isEmpty()) return;

            /**
             * 月运费单编号
             */
            monthFreightBillNumber = OrderUtils.getOrderNumber("MF", "-");

            /**
             * 运费总额，四舍五入，保留2位小数
             */
            monthFreightWeightTotal = Math.round(monthFreightWeightTotal * 1000.0) / 1000.0;
            monthFreightAmountTotal = Math.round(monthFreightAmountTotal * 100.0) / 100.0;

            /**
             * 月运费单，数据准备
             */
            tFreightBillInfo.setFreightBillNumber(monthFreightBillNumber);
            tFreightBillInfo.setFreightBillDate(Date.valueOf(lastMonthDate));
            tFreightBillInfo.setStatisticFieldName(freightSettlementCustomer);
            tFreightBillInfo.setFreightWeightTotal(monthFreightWeightTotal);
            tFreightBillInfo.setFreightAmountTotal(monthFreightAmountTotal);
            tFreightBillInfo.setFreightCollectionStatus("未付款");
            tFreightBillInfo.setStatisticField("结费客户");
            tFreightBillInfo.setStatisticGranularity("月账单");
            tFreightBillInfo.setCreateBy("system");
            tFreightBillInfo.setCreateTime(DateUtils.getNowDate());

            /**
             * 月运费单，插入数据
             */
            tFreightBillInfoService.insertTFreightBillInfo(tFreightBillInfo);
            sleep(300);

            /**
             * 获取插入记录，ID
             */
            monthFreightBillId = tFreightBillInfoService.selectFreightBillIdByFreightBillNumber(monthFreightBillNumber);
//            logger.debug("OOO " + "salaryBillId = " + salaryBillId);

            /**
             * monthFreightAmountTotal清零
             */
            monthFreightWeightTotal = 0.0;
            monthFreightAmountTotal = 0.0;


            /**
             * 运费运单关联表，数据插入
             */
//            logger.debug("OOO " + "wayBillIds = " + wayBillIds);
            tFreightWayBillRelService.insertTFreightWayBillRelExt(monthFreightBillId, wayBillIds);
            wayBillIds.clear();
        }

        logger.debug("统计，月运费单，月账单，按结算客户，结束 ...");
    }

}
